package com.iqunxing.redis.redisInAction.ch02;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class LoginCookieService {

    private static final Long LIMIT = 5L;

    @Autowired
    private RedisTemplate<String, String> template;

    /**
     * 尝试获取并返回登陆的用户.
     *
     * @param token
     *            the token
     * @return the string
     */
    public String checkToken(String token) {
        return (String) template.boundHashOps("login:").get(token);
    }

    /**
     * 更新token.
     *
     * @param token
     *            the token
     * @param user
     *            the user
     * @param item
     *            the item
     */
    public void updateToken(String token, String user, String item) {
        Long time = System.currentTimeMillis();
        template.boundHashOps("login:").put(token, user);
        template.boundZSetOps("recent:").add(token, time);
        if (StringUtils.isNotBlank(item)) {
            BoundZSetOperations<String, String> viewedOps = template.boundZSetOps("viewed:" + token);
            viewedOps.add(item, time);
            viewedOps.removeRange(0, -26);
        }
    }

    /**
     * 清除当前的缓存.
     *
     * @param limit
     *            the limit
     */
    public void cleanSession(int limit) {
        long size = template.boundZSetOps("recent:").size();
        // 需要清除
        if (size > limit) {
            long end = Math.min(size - LIMIT, 100);
            Set<String> tokens = template.boundZSetOps("recent:").range(0, end);
            for (String token : tokens) {
                template.delete("viewed:" + token);
                template.boundHashOps("login:").delete(token);
                template.boundZSetOps("recent:").remove(token);
            }
        }
    }

}
